package com.opdar.platform.core.convert;

import org.springframework.cglib.core.ReflectUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by shiju on 2017/1/19.
 */
public class ObjectConvertInvocationHandler implements InvocationHandler {
    private final Class type;
    private Map<String, ParameterConvert> convertMap;

    public ObjectConvertInvocationHandler(Class type, Map<String, ParameterConvert> convertMap) {
        this.type = type;
        this.convertMap = convertMap;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = ReflectUtils.newInstance(type);
        int count = 0;
        HashMap<String,?> parameters = (HashMap<String,?>) args[0];
        for(Iterator<String> it = parameters.keySet().iterator(); it.hasNext();)
            try {
                String name = it.next();
                if(convertMap.containsKey(name.toLowerCase())){
                    Field field = type.getDeclaredField(name);
                    field.setAccessible(true);
                    Object parameter = parameters.get(name);
                    ParameterConvert convert = convertMap.get(name.toLowerCase());
                    parameter = convert.convert(parameter);
                    if(parameter!=null){
                        count++;
                        field.set(result,parameter);
                    }
                }
            } catch (NoSuchFieldException ignored) {}
        return count > 0?result:null;
    }
}
